<template>
  <!--选规格-->
  <div class="scroll-hide">
    <van-popup v-model="show2" position="center" round @close="close" style="background: transparent">
      <div class="spec_big_box">
        <!-- <h3 class="title">
          <span class="spec_big_box_title">{{ popTitle }}</span>
          <i @click.stop="close" class="iconfont icon-close11"></i>
        </h3> -->
        <div class="headGood">
          <div class="headGood_l">
            <img :src="goodsInfo.thumb" alt="" />
          </div>
          <div class="headGood_r">
            <div class="headGood_r_t">{{ goodsInfo.title }}</div>
            <div class="sku_r">库存{{ popStock }}</div>
          </div>
        </div>
        <div class="spec_box q5" :style="{ width: fun.getPhoneEnv() == 3 ? '375px' : '100%' }">
          <div class="spec_a">
            <div v-for="(spec, i) in goodsInfo.has_many_specs" :key="i">
              <h5>{{ spec.title }}：</h5>
              <ul class="option">
                <li @click.stop="selectSpecs(item, item.id)" v-for="(item, i) in spec.specitem" :key="i" :class="specid.indexOf(item.id) >= 0 ? 'cur' : ''">
                  {{ item.title }}
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="add_car">
          <ul class="car_btn">
            <li class="left">
              <span>{{ $i18n.t("money") }}</span
              >{{ popPrice }}
              <!-- <span style="margin-left: 0.3rem;">库存：{{ popStock }}</span> -->
            </li>

            <div class="Box" v-if="checkCartJson(goodsInfo)">
              <van-stepper
                @blur="inpblur(checkCartJson(goodsInfo).total)"
                @focus="focus(checkCartJson(goodsInfo).total)"
                @minus="updateCartChild(popCard.id, -1)"
                @plus="updateCartChild(popCard.id, 1)"
                :style="{ '--color': `${themeColor}` }"
                v-model="checkCartJson(goodsInfo).total"
                theme="round"
                button-size="20"
                min="0"
              />
            </div>
            <li class="right" v-else>
              <span @click.stop="submitAction">加入购物车</span>
              <!-- <span v-show="popStock <= 0" style="background: #999">库存不足</span> -->
            </li>
          </ul>
        </div>
      </div>
      <i class="iconfont icon-adsystem_icon_cancle" @click="close"></i>
    </van-popup>
  </div>
</template>
<script>
var specsManage = []; //选择池 用于排序
var optionsId = ""; //选择后的 规格ID
var optionsMaxCount = 1;
export default {
  model: {
    prop: "show2",
    event: "onEmit"
  },
  props: {
    show2: {
      type: Boolean,
      default: false
    },
    goodsInfo: {
      type: Object,
      default: {}
    },
    carts: {
      type: null
    },
    store_id: {
      tyep: null
    },
    themeColor:{
      type:String,
      default:"#f14e4e"
    }
  },
  data() {
    return {
      moreCate: "",
      specid: "", //规格ID
      popNum: 0,
      goodsCartsOld: ""
    };
  },
  watch: {
    show2: function (nval, oval) {
      if (nval) {
        //价格权限
        if (this.goodsInfo.vip_level_status && this.goodsInfo.vip_level_status.status == 1) {
          Toast(this.goodsInfo.vip_level_status.tips);
          return false;
        }
        this.show2 = true;
        // this.goodsInfo = good;

        this.initPopView(); //初始化弹窗view
      }
    },
    carts: function (nval, oval) {
      if (nval) {
        this.initSpecs();
      }
    }
  },
  computed: {
    checkCartJson(item) {
      return function (item) {
        let arrayA = this.carts;
        console.log(arrayA,this.carts,'dddddddddddddddddddd')
        if (this.carts.length == 0) return false;
        let arr = [];
        console.log(arrayA,this.carts,'2222')
        for (let i = 0; i < arrayA.length; i++) {
          if (arrayA[i].goods_id == item.id) {
            if (arrayA[i].goods_option && arrayA[i].goods_option.id == optionsId) {
              arr = arrayA[i];
              break;
            }
          }
        }
        if (arr.length <= 0) {
          return false;
        } else {
          return arr;
        }
      };
    }
  },
  methods: {
    inpblur(num) {
      console.log(num < this.goodsCartsOld);
      if (num === 0) {
        this.delItemByCart({id:this.popCard.id})
        return;
      }
      if (num == "") {
        console.log(num, this.goodsCartsOld);
        return;
      } else if (num < this.goodsCartsOld) {
        let lowerNum = `-${this.goodsCartsOld - num}`;
        // this.$emit("change", { id: this.popCard.id, key: "blur", lowerNum });
        this.updateCartRequest(this.popCard.id, lowerNum);
      } else if (num > this.goodsCartsOld) {
        let lowerNum = num - this.goodsCartsOld;
        this.updateCartRequest(this.popCard.id, lowerNum);
      } else if (num == this.goodsCartsOld) {
        return;
      }
    },
    focus(num) {
      this.goodsCartsOld = num;
      console.log(this.goodsCartsOld);
    },
    close() {
      this.$emit("close");
    },
    updateCartChild(id, key) {
      // 购物车操作
      console.log(id, key, "购物车操作 + -");
      if (key == "1") {
        this.updateCartRequest(id, key);
      } else if (key == "-1") {
        this.updateCartRequest(id, key);
      }
      // this.$emit("change", { id, key });
    },
    submitAction() {
      console.log("第一次加入购物车", this.goodsInfo.id, optionsId);
      let json = { id: this.goodsInfo.id, option_id: optionsId };
      this.addCart(json, "");
    },
    //  +  -操作
    updateCartRequest(id, num) {
      $http
        .get(
          "plugin.store-cashier.frontend.shoppingCart.member-cart.updateNum",
          {
            id: id,
            num: num,
            store_id: this.store_id
          },
          "加载中"
        )
        .then(
          response => {
            this.cartPostClick = true;
            if (response.result == 1) {
              this.$emit("updateCart");
            } else {
              this.$dialog.alert({ message: response.msg });
            }
          },
          response => {}
        );
    },
    // 首次进入购物车
    addCart(goods, tag, _i) {
      let id = "";
      if (tag === "cart") {
        id = goods.goods_id;
      } else {
        id = goods.id;
      }
      $http
        .get(
          "plugin.store-cashier.frontend.shoppingCart.member-cart.store",
          {
            goods_id: id,
            total: 1,
            store_id: this.store_id,
            option_id: goods.option_id || 0
          },
          "添加中"
        )
        .then(
          response => {
            this.cartPostClick = true;
            if (response.result === 1) {
              console.log("manySpecs请求更新购物车");
              this.$emit("updateCart");
              // this.getCart(goods);
            } else {
              this.$dialog.alert({ message: response.msg });
            }
          },
          response => {
            //alert('网络错误，请稍后再试！')
          }
        );
    },
    // 移除购物车
    delItemByCart(cart_id) {
      $http
        .get("plugin.store-cashier.frontend.shoppingCart.member-cart.destroy", {
          store_id: this.store_id,
          ids: cart_id.id
        },"")
        .then(
          response => {
            if (response.result == 1) {
              this.$emit("updateCart");
            } else {
              this.$dialog.alert({ message: response.msg });
            }
          },
          response => {
            //alert('网络错误，请稍后再试！')
          }
        );
    },
    //初始化弹窗view
    initPopView(key) {
      optionsId = "";
      specsManage = [];
      this.specid = "";
      this.popNum = 0;
      if (this.goodsInfo.has_option === 1) {
        //是否有规格
        this.popTitle = this.goodsInfo.title; //设置默认图片
        this.popThumb = this.goodsInfo.thumb; //设置商品名
        this.popStock = this.goodsInfo.stock; //设置默认库存
        this.popCard = {};
        if (!this.specid.length) {
          this.popPrice = this.goodsInfo.min_price + "-" + this.goodsInfo.max_price; //设置默认价格
        }

        this.goodsDescription = "请选择";
        for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
          this.goodsDescription += " " + this.goodsInfo.has_many_specs[i].title;
        }
        if (!optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
            this.selectSpecs(this.goodsInfo.has_many_specs[i].specitem[0], this.goodsInfo.has_many_specs[i].specitem[0].id);
          }
        }
      } else {
        this.goodsDescription = "";
        optionsMaxCount = this.goodsInfo.stock; //设置最大购买量
      }
    },
    initSpecs() {
      for (let i = 0; i < this.carts.length; i++) {
        if (this.carts[i].goods_id === this.goodsInfo.id && this.carts[i].option_id === optionsId) {
          this.popNum = this.carts[i].total;
          this.popCard = this.carts[i];
          break;
        }
        this.popNum = 0;
        this.popCard = {};
      }
    },
    //界面选择规格触发事件
    selectSpecs(data, id) {
      //处理选择池
      this.manageSpecs(data);

      //处理规格组合选择状态
      this.setGoodsSpecs(data);

      //设置选择规格后的 价格、照片、库存
      this.setGoodsSpecsChangeInfo(id);

      //判断当前购买总量与库存的关系
      this.getMaxCount();
    },
    //判断当前购买总量与库存的关系
    getMaxCount() {
      if (specsManage.length == this.goodsInfo.has_many_specs.length) {
        if (optionsMaxCount == 0) {
          //库存不足
          this.popNum = 0;
        }
        if (this.popNum > optionsMaxCount) {
          this.popNum = optionsMaxCount;
        }
      }
    },
    //处理选择池
    manageSpecs(data) {
      var specsObject = new Object();
      specsObject.id = data.id;
      specsObject.specid = data.specid;
      specsObject.title = data.title;

      if (specsManage.length > 0) {
        for (let i = 0; i < specsManage.length; i++) {
          if (specsManage[i].specid == specsObject.specid) {
            specsManage.splice(i, 1);
          }
        }
        specsManage.push(specsObject);
      } else {
        specsManage.push(specsObject);
      }

      //排序
      if (specsManage.length == this.goodsInfo.has_many_specs.length) {
        var newSpecsManage = [];
        for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
              newSpecsManage.push(specsManage[j]);
              break;
            }
          }
        }
        specsManage = newSpecsManage;
      }
      this.setGoodsDescription();
    },
    //处理goodsDescription 数据
    setGoodsDescription() {
      var description = "";
      //相等代表全选了 体现语句
      if (specsManage.length == this.goodsInfo.has_many_specs.length) {
        description = "已选择 ";
        for (let i = 0; i < specsManage.length; i++) {
          description += specsManage[i].title + " ";
        }
        this.goodsDescription = description;
      } else {
        description = "请选择 ";

        for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
              description += this.goodsInfo.has_many_specs[i].title + " ";
              break;
            }
          }
        }
        this.goodsDescription = description;
      }
    },
    //处理规格组合选择状态 过滤数据
    setGoodsSpecs(specs) {
      for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
        if (specs.specid != this.goodsInfo.has_many_specs[i].id) {
          this.setGoodsSpecsStatus(this.goodsInfo.has_many_specs[i].specitem, specs.id);
        }
      }
    },

    //处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
    setGoodsSpecsStatus(specitem, id) {
      let options = []; //数据池

      for (let i = 0; i < this.goodsInfo.has_many_options.length; i++) {
        let _specs = this.goodsInfo.has_many_options[i].specs.split("_");
        //判断是否包含
        for (let j = 0; j < _specs.length; j++) {
          if (_specs[j] == id) {
            options.push(this.goodsInfo.has_many_options[i]);
          }
        }
      }

      for (let m = 0; m < options.length; m++) {
        let _specs = options[m].specs.split("_");
        for (let y = 0; y < _specs.length; y++) {
          if (_specs[y] != id && options[m].stock == 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = true;
              }
            }
          } else if (_specs[y] != id && options[m].stock > 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = false;
              }
            }
          }
        }
      }
    },
    //处理商品goodsSpecs 并排序 新方法
    setGoodsSpecsBySort(specs) {
      let _specs = specs.split("_"); //先变成数组
      //_specs.sort();//排序
      _specs.sort(function (a, b) {
        return a - b;
      });

      // 在组装回去
      let goodsSpecs = "";
      for (let j = 0; j < _specs.length; j++) {
        goodsSpecs += _specs[j] + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"

      return goodsSpecs;
    },
    //设置选择规格后的 价格、照片、库存
    setGoodsSpecsChangeInfo(id) {
      //根据ID 排序 specsManage.sort();
      specsManage.sort(function (a, b) {
        return a.id - b.id;
      });
      if (specsManage.length === this.goodsInfo.has_many_specs.length) {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"
        this.specid = goodsSpecs;
        for (let i = 0; i < this.goodsInfo.has_many_options.length; i++) {
          if (goodsSpecs === this.setGoodsSpecsBySort(this.goodsInfo.has_many_options[i].specs)) {
            this.popmPrice = this.goodsInfo.has_many_options[i].market_price; //设置价格
            this.popPrice = this.goodsInfo.has_many_options[i].product_price; //设置价格
            this.popThumb = this.fun.isTextEmpty(this.goodsInfo.has_many_options[i].thumb) ? this.goodsInfo.thumb : this.goodsInfo.has_many_options[i].thumb; //设置图片
            this.popStock = this.goodsInfo.has_many_options[i].stock; //设置库存

            optionsId = this.goodsInfo.has_many_options[i].id; //设置规格ID，用于生成订单
            optionsMaxCount = this.goodsInfo.has_many_options[i].stock; //库存最大数 用于切换更改买家购买数量
            if (optionsMaxCount > 0) {
              this.popNum = 0;
            }

            break;
          }
        }

        for (let i = 0; i < this.carts.length; i++) {
          if (this.carts[i].goods_id === this.goodsInfo.id && this.carts[i].option_id === optionsId) {
            this.popNum = this.carts[i].total;
            this.popCard = this.carts[i];
            break;
          }
          this.popNum = 0;
          this.popCard = {};
        }
      } else {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        this.specid = goodsSpecs;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.title {
  border-radius: 0.625rem 0.625rem 0 0;
  width: 100%;
  background-color: #fff;
  line-height: 2.75rem;
  font-size: 16px;
  position: absolute;
  top: 0;

  i {
    position: absolute;
    right: 0.875rem;
    line-height: 2.75rem;
    color: #999;
    font-size: 1.125rem;
  }
}
.icon-adsystem_icon_cancle {
  font-size: 2rem;
  color: #fff;
}
.spec_big_box {
  position: relative;
  background: #fff;
  width: 20rem;
  height: 24.5rem;
  border-radius: 0.94rem;
  padding: 0.75rem;
  box-sizing: border-box;
  overflow: hidden;
  margin-bottom: 1rem;
  .headGood {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    .headGood_l {
      flex-shrink: 0;
      width: 3.75rem;
      height: 3.75rem;
      img {
        width: 100%;
        height: 100%;
        border-radius: 0.5rem;
      }
    }
    .headGood_r {
      margin-left: 0.59rem;
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      .headGood_r_t {
        font-size: 0.88rem;
        font-weight: 500;
        color: #3b3b4a;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
      .sku_r {
        font-size: 0.81rem;
        font-weight: 400;
        color: #aaaab3;
        margin-top: 0.41rem;
      }
    }
  }
  .spec_big_box_title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: inline-block;
    width: 19rem;
  }
}
.spec_box {
  background: #fff;
  height: 17.375rem;
  overflow-y: scroll;
  // position: absolute;
  top: 2.5rem;

  .spec_a {
    margin-top: 0.625rem;

    h5 {
      display: block;
      line-height: 2.5rem;
      text-align: left;
      color: #6e6e79;
      font-size: 0.81rem;
      // padding-left: 1.25rem;
    }

    .option {
      display: flex;
      padding: 0 0rem;
      flex-wrap: wrap;

      .cur {
        border: solid 0.0625rem var(--themeBaseColor);
        background: #faf0f0;
        color: var(--themeBaseColor);
      }

      li {
        cursor: pointer;
        padding: 0 6px;
        min-height: 1.875rem;
        line-height: 1.875rem;
        margin-right: 0.625rem;
        margin-bottom: 0.625rem;
        background: #f5f5f5;
        border: solid 0.0625rem #ebebeb;
        border-radius: 0.1875rem;
      }
    }
  }
}
.add_car {
  width: 100%;
  // height: 3.4375rem;
  // line-height: 3.4375rem;
  background-color: #fff;
  // border-top: solid 0.0625rem #ebebeb;
  // border-radius: 0 0 0.625rem 0.625rem;
  // position: absolute;
  // bottom: 0;

  .car_btn {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding: 0 0.875rem;

    .left {
      flex: 1;
      color: #f15353;
      font-size: 1.31rem;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-align: left;

      span {
        font-size: 0.68rem;
      }
    }

    .right {
      flex-shrink: 0;
    }
    .right span {
      display: block;
      // width: 5.5625rem;
      // height: 1.875rem;
      font-size: 0.81rem;
      line-height: 1.13rem;
      padding: 0.59rem 1rem;
      border-radius: 1rem;
      background: var(--themeBaseColor);
      color: #fff;
      font-size: 14px;
    }
  }
}

.Box {
  position: absolute;
  bottom: 0.625rem;
  right: 0.625rem;
  display: flex;

  .iconfont {
    width: 1.75rem;
    height: 1.75rem;
    line-height: 1.75rem;
    font-size: 26px;
    color: var(--themeBaseColor);
  }

  .icon-store_reduceLine {
    color: #aaa;
  }

  input {
    width: 2rem;
    text-align: center;
    font-size: 12px;
  }
}

.Box label {
  right: 2.1875rem;
  color: #333;
  font-size: 12px;
  padding: 0;
  width: 1.5rem;
  height: 1.75rem;
  overflow: hidden;
  display: inline-block;
  text-align: center;
  line-height: 1.75rem;
  vertical-align: top;
  -webkit-background-origin: content-box;
  background-origin: content-box;
  background-color: transparent;
}

.Box .hide {
  display: none;
}
.van-stepper {
  ::v-deep .van-stepper__minus {
    color: var(--color);
    border-color: var(--color);
  }

  ::v-deep .van-stepper__plus {
    background-color: var(--color);
  }
}
</style>
